package com.ncmmall.api.security.interceptor;

import com.ncmmall.api.apis.service.Result;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author linxs
 * 权限拦截器
 */
@Component
@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {

    /**
     * 临时对象，不可用
     */
    @Autowired
    private QueryChannelService queryChannelService;

    public static QueryChannelService querychannelservice;

    @PostConstruct
    public void init() {
        AuthorizationInterceptor.querychannelservice = queryChannelService;
    }

    /**
     * 请求方法处理前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        if (Strings.isNullOrEmpty(request.getHeader("Authorization"))) {
            Result result = new Result();
            result.forbidden().setMsg("未登录");
            writeResponse(response, result);
            return false;
        }

        WebUser user = querychannelservice.queryOneEntity("select u.* from security_web_user u where u.accessToken = :token ", ImmutableMap.of("token", request.getHeader("Authorization")), WebUser.class);

        if (null == user) {
            Result result = new Result();
            result.forbidden().setMsg("登录信息已过期");
            writeResponse(response, result);
            return false;
        }

        return true;

    }

    /**
     * 处理请求完成后，视图渲染前执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) {
    }

    /**
     * 视图渲染后执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
    }

    private void writeResponse(ServletResponse response, Result result) throws IOException {
        JSONObject responseJSONObject = JSONObject.fromObject(result);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(responseJSONObject.toString());
        out.close();
    }

}
